//
//  CZHomePictureView.swift
//  CZVVeiBo
//
//  Created by smile on 2017/8/3.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
import SDWebImage
// cell 间距
private let cellMargin: CGFloat = 5
// 计算cell的宽高
private let cellWH = (CZSCREENW - 20 - cellMargin*2)/3
class CZHomePictureView: UICollectionView {
    
    // 提供属性供外界赋值
    var picUrls:[CZPictureUrlModel]?{
        didSet{
            // 计算大小
            let size = dealPictureViewSize(count: picUrls!.count)
            // 更新约束
            snp.updateConstraints { (make) in
                make.size.equalTo(size)
            }
            // 刷新
            reloadData()
            
        }
    }
    
    // MARK: - 通过配图数组的个数计算配图的大小
    fileprivate func dealPictureViewSize(count: Int) -> CGSize{
        // 得到flowLayout
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        // 如果是一张图片
        if count == 1 {
            // 通过key获取本地图片 判断是否为nil
            if let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: picUrls?.first?.thumbnail_pic){
                
                // 计算image 的宽和高
                var w = image.size.width
                var h = image.size.height
                // 如果宽度小于80 就==80
                if w < 80{
                    w = 80
                }
                // 如果高度大于150 就==150
                if h > 150 {
                    h = 150
                }
                // itemSize
                flowLayout.itemSize = CGSize(width: w, height: h)
                return CGSize(width: w, height: h)
            }
        }
        // 计算行数和列数
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        let col = count == 4 ? 2 :  count >= 3 ? 3 : count
        // 计算配图的宽和高
        let w = CGFloat(col)*cellWH + CGFloat(col -  1)*cellMargin
        let h = CGFloat(row)*cellWH + CGFloat(row -  1)*cellMargin
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        return CGSize(width: w, height: h)
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        // itemSize
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        // cell 间距
        flowLayout.minimumLineSpacing = cellMargin
        flowLayout.minimumInteritemSpacing = cellMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        // 设置数据源
        dataSource = self
        // 注册
        register(CZHomePictureViewCell.self, forCellWithReuseIdentifier: "cell")
    }

}
// MARK: - UICollectionViewDataSource
extension CZHomePictureView: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CZHomePictureViewCell
        // 赋值
        cell.pic_url = picUrls![indexPath.item]

        return cell
    }
}

// MARK: - 自定义cell
class CZHomePictureViewCell: UICollectionViewCell {
    
    // 提供一个属性供外界赋值
    var pic_url: CZPictureUrlModel?{
        didSet{
           // 赋值
            bgImageView.cz_setImage(urlString: pic_url?.thumbnail_pic, placeholderImgName: "timeline_image_placeholder")
//            print(pic_url?.thumbnail_pic)
            // http://wx4.sinaimg.cn/thumbnail/9fe432b5gy1fi7sux2qaqj21120kugoo.gif"
            
            if let thumbnail_pic = pic_url?.thumbnail_pic, thumbnail_pic.hasSuffix(".gif"){
                // 是gif图片
                gifImageView.isHidden = false
            }else{
                gifImageView.isHidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = randomColor()
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        bgImageView.snp.makeConstraints { (make) in
            make.left.top.bottom.right.equalTo(contentView)
        }
        
        gifImageView.snp.makeConstraints { (make) in
            make.right.bottom.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    // 背景图片
    private lazy var bgImageView: UIImageView = {
        let img = UIImageView(imgName: "timeline_image_placeholder")
        // 图片填充方式
        img.contentMode = .scaleAspectFill
        // 超出部分要裁剪掉
        img.clipsToBounds = true
        return img
    }()
    // gif
    private lazy var gifImageView: UIImageView = UIImageView(imgName: "timeline_image_gif")
}











